<?php

require_once 'forms/LoginForm.php';

class LoginController extends Zend_Controller_Action {
    
    public function init() {
        parent::init();
        $this->view->headScript()->appendFile('/js/jquery.min.js');
        $this->view->headLink()->appendStylesheet('/styles/login.css');
    }

    public function indexAction() {

        $form = new LoginForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {

                $adapter = $this->getAuthAdapter($form->getValues());
                $auth = Zend_Auth::getInstance();

                $result = $auth->authenticate($adapter);

                if (!$result->isValid()) {


                    // Credencial inválida
                    $auth->clearIdentity();
                    $form->setDescription('Invalid access data');
                    $this->view->assign('msg', array('Invalid access data'));
                } else {

                    $aclUsuarios = $adapter->getResultRowObject();
                    
                    $sessao = new Zend_Session_Namespace('auth_user');
                    $sessao->dados = $aclUsuarios;
                    
                    $redirUrl = new Zend_Session_Namespace('redir');
                    if (!empty($redirUrl->url)) {
                        //se tiver redirecionamento registrado, envia para o local
                        $url = $redirUrl->url;
                        $redirUrl->unsetAll();
                        $this->_redirect($url);
                    } else {
                        // Se estiver autenticado, redireciona para a area administrativa (action, controller, module)
                        $registry = Zend_Registry::getInstance();
                        if($sessao->dados->gru_codigo == 1){
                            $this->_redirect($this->view->serverUrl()."/index.php");
                        }else{
                            prpre('Usuário');
                        }
                    }
                }
            } else {
                $this->view->assign('msg', array('Invalid access data'));
            }
        }

        $this->view->form = $form;
        $this->_helper->layout->setLayout('login');
    }

    /**
     * @param $params array
     * @return Zend_Auth_Adapter_DbTable object
     */
    public function getAuthAdapter(array $params) {

        $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());

        //setando as colunas e as tabelas
        $authAdapter->setIdentityColumn('usu_login');
        $authAdapter->setCredentialColumn('usu_senha');
        $authAdapter->setTableName('usuario');
        //setando os dados
        $authAdapter->setIdentity($params['usu_login']);
        $authAdapter->setCredential(sha1($params['usu_senha']));

        return $authAdapter;
    }
    
    
    public function preDispatch() {

        $this->_helper->layout->setLayout('login');

        if (Zend_Auth::getInstance()->hasIdentity()) {
            // Se o usuario estiver logado, nos nao exibimos o formulario de login;
            // a nao ser que tenha chamado o metodo logout
            if ('logout' != $this->getRequest()->getActionName()) {
                $this->_redirect($this->view->serverUrl()."/index.php");
            }
        } else {
            // Se o usuario não chamou o metodo logout então
            // redirecionamos para o formumario de login
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_redirect($this->view->serverUrl()."/login.php");
            }
        }
    }
    
    /**
     * Encerra a sessão
     *
     */
    public function logoutAction() {
        Zend_Session::destroy();
        $this->_redirect($this->view->serverUrl()."/login");
    }

}

?>
